<?php

class Jssdk
{
    public $appId;
    public $appSecret;
    const TicketPath = 'jsapi_ticket.json';
    const TokenPath = 'access_token.json';
    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getSignPackage($boo = false)
    {
        if ($boo){
            return [];
        }
        $jsapiTicket = $this->getJsApiTicket();
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket()
    {
    	if ( ! file_exists(self::TicketPath) ){
    		file_put_contents(self::TicketPath, '');
    	}
    	
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
    	$data = json_decode(file_get_contents(self::TicketPath),true);
    	if ( ! isset($data->expire_time) || $data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            $ticket = $this->ticket($accessToken);
            if ($ticket) {
                $data['expire_time'] = time() + 7000;
                $data['jsapi_ticket'] = $ticket;
                $fp = fopen(self::TicketPath, "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }

    /**
     * 获取AccessToken 【微信接口调用参数】
     * @return boolean|mixed
     */
    public function getAccessToken()
    {
    	if ( ! file_exists(self::TokenPath) ){
    		file_put_contents(self::TokenPath, '');
    	}
    	
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    	$data = json_decode(file_get_contents(self::TokenPath),true);

    	if ( ! isset($data['expire_time']) || $data['expire_time'] < time()) {
            $access_token = $this->get_access_token($this->appId, $this->appSecret);
            if ($access_token) {
                $data['expire_time'] = time() + 7000;
                $data['access_token'] = $access_token;
                $fp = fopen(self::TokenPath, "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data['access_token'];
        }
        return $access_token;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    /**
     * 获取 ACCESS_TOKEN
     * $appid：appid
     * $appsecret：appsecret
     */
    private function get_access_token($appid,$appsecret){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        curl_close($ch);
        if(!empty($output)){
            $json=json_decode($output,true);
            if(isset($json['access_token'])){
                return $json['access_token'];
            }else{
            	//p($output);
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 获取 ticket
     * $accesstoken
     */
    private function ticket($accesstoken){
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token='.$accesstoken;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        curl_close($ch);
        if(!empty($output)){
            $json=json_decode($output, true);
            if(isset($json['ticket'])){
                return $json['ticket'];
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    
    public function curl_get_contents($url){
    	
    	$ch=curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:26.0) Gecko/20100101 Firefox/26.0");
    	curl_setopt($ch, CURLOPT_REFERER,$url);
    	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	$r = curl_exec($ch);
    	curl_close($ch);
    	return $r;
    }
    
    /**
     *  curl POST 会话访问模式
     * @param $url
     * @param $arr
     * @return mixed
     */
    public function curl_post_contents($url,$arr)
    {
    	$ch=curl_init();//初始化
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_HEADER, 0);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	curl_setopt($ch, CURLOPT_POST,1);
    	curl_setopt($ch, CURLOPT_POSTFIELDS,$arr);
    	$re = curl_exec($ch);//运行
    	curl_close($ch);
    	return $re;
    }
}

